<template>
  <div class="order-table-container">
    <!-- 状态筛选区域 -->
    <div class="filter-area">
      <el-select
          v-model="selectedStatus"
          placeholder="选择订单状态"
          style="width: 240px"
          @change="handleStatusChange"
      >
        <el-option
            v-for="(item, index) in statusOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>

    <!-- 表格容器 -->
    <div class="table-wrapper">
      <el-table
          :data="filteredOrders"
          border
          stripe
          style="width: 100%"
          :loading="tableLoading"
          @selection-change="handleSelectionChange"
      >
        <!-- 自增编号列 -->
        <el-table-column label="编号" width="100">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <!-- 订单编号 -->
        <el-table-column prop="order_no" label="订单编号" width="360" />
        <!-- 用户名 -->
        <el-table-column label="用户账户" width="200">
          <template #default="scope">
            {{ scope.row.user?.username || '-' }}
          </template>
        </el-table-column>
        <!-- 支付状态 -->
        <el-table-column label="支付状态" width="200">
          <template #default="scope">
            <el-tag
                :type="statusTagType(scope.row.status)"
                :color="statusTagColor(scope.row.status)"
            >
              {{ statusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 支付金额 -->
        <el-table-column label="支付金额" width="250">
          <template #default="scope">
            ¥{{ (scope.row.total_amount ).toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="193">
          <template #default="scope">
            <el-button
                size="small"
                type="info"
                @click="handleDetail(scope.row)"
                icon="InfoFilled"
            >
              查看详情
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                icon="DeleteFilled"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态提示 -->
      <div v-if="filteredOrders.length === 0 && !tableLoading" class="empty-state">
        <el-empty description="暂无订单数据" />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="800px"
        destroy-on-close
    >
      <el-form :model="currentOrder" label-width="120px" size="default">
        <!-- 订单编号 -->
        <el-form-item label="订单编号">
          <el-input v-model="currentOrder.order_no" disabled />
        </el-form-item>

        <!-- 商品信息表格 -->
        <el-form-item label="商品信息">
          <el-table
              :data="currentOrder.products || []"
              border
              size="small"
              style="width: 100%"
              max-height="200"
          >
            <el-table-column prop="prod_name" label="商品名称" width="220" />
            <el-table-column prop="count" label="数量" width="100" align="center" />
            <el-table-column label="单价" align="center">
              <template #default="scope">
                ¥{{ (scope.row.prod_price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="小计" align="center">
              <template #default="scope">
                ¥{{ ((scope.row.prod_price * scope.row.count)).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 下单时间 -->
        <el-form-item label="下单时间">
          <el-input :value="formatDateTime(currentOrder.create_time)" disabled />
        </el-form-item>

        <!-- 支付时间 -->
        <el-form-item label="支付时间">
          <el-input :value="currentOrder.pay_time ? formatDateTime(currentOrder.pay_time) : '未支付'" disabled />
        </el-form-item>

        <!-- 支付方式 -->
        <el-form-item label="支付方式">
          <el-input :value="payTypeText(currentOrder.pay_type)" disabled />
        </el-form-item>

        <!-- 收件人信息 -->
        <el-form-item label="收件人">
          <el-input :value="currentOrder.address?.receiver || '-'" disabled />
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话">
          <el-input :value="currentOrder.address?.phone || '-'" disabled />
        </el-form-item>

        <!-- 收货地址 -->
        <el-form-item label="收货地址">
          <el-input :value="currentOrder.address?.address || '-'" disabled />
        </el-form-item>

        <!-- 支付状态 -->
        <el-form-item label="支付状态">
          <el-input :value="statusText(currentOrder.status)" disabled />
        </el-form-item>

        <!-- 订单金额 -->
        <el-form-item label="订单金额">
          <el-input :value="`¥${(currentOrder.total_amount ).toFixed(2)}`" disabled />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="handleShip"
            :disabled="currentOrder.status !== 1"
        >
          去发货
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="30%"
        destroy-on-close
    >
      <p>您确定要删除订单 <span class="text-primary font-medium">{{ deleteOrderNo }}</span> 吗？此操作不可撤销。</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus'
// 引入API请求（请根据实际项目结构调整路径）
import orderApi from '@/api/order.js'

// ===================== 核心数据 =====================
// 订单列表（原始数据）
const orders = ref([])
// 筛选后的订单列表
const filteredOrders = ref([])
// 表格加载状态
const tableLoading = ref(false)
// 选中的订单（批量操作备用）
const selectedOrders = ref([])

// ===================== 状态筛选 =====================
// 选中的状态
const selectedStatus = ref(1)
// 状态选项
const statusOptions = ref([
  { label: '待支付', value: 0 },
  { label: '已支付', value: 1 },
  { label: '已发货', value: 2 },
  { label: '已完成', value: 3 }
])

// ===================== 详情弹窗 =====================
// 弹窗显示状态
const dialogVisible = ref(false)
// 弹窗标题
const dialogTitle = ref('订单详情')
// 当前选中的订单
const currentOrder = ref({
  id: '',
  order_no: '',
  user: {},
  address: {},
  products: [],
  pay_type: 0,
  total_amount: 0,
  status: 0,
  create_time: '',
  pay_time: '',
  delivery_time: ''
})

// ===================== 删除弹窗 =====================
// 删除弹窗显示状态
const deleteDialogVisible = ref(false)
// 待删除订单ID
const deleteOrderId = ref('')
// 待删除订单编号
const deleteOrderNo = ref('')

// ===================== 页面挂载时加载数据 =====================
onMounted(async () => {
  orders.value = await orderApi.getOrderList(selectedStatus.value)
  filterOrdersByStatus()
})

// ===================== API请求 =====================
/**
 * 获取订单列表
 */
const fetchOrderList = async () => {
  try {
    tableLoading.value = true
    // 调用后端API（根据实际接口调整参数）
    const response = await orderApi.getOrderList(selectedStatus.value)
    // 适配后端数据结构
    if ( Array.isArray(response)) {
      orders.value = response
      // 关键：重新筛选数据
      filterOrdersByStatus();
    } else {
      orders.value = []
      filteredOrders.value = []
      ElMessage.warning('获取订单列表为空')
    }
  } finally {
    tableLoading.value = false
  }
}

/**
 * 删除订单
 */
const deleteOrder = async (orderId) => {
  try {
    tableLoading.value = true
    // 调用删除API（根据实际接口调整）
    const response = await orderApi.deleteOrder(orderId)
      // 重新加载订单列表
      await fetchOrderList()
  } finally {
    tableLoading.value = false
  }
}

/**
 * 订单发货
 */
const shipOrder = async (orderId) => {
  try {
    tableLoading.value = true
    // 调用发货API（根据实际接口调整）
    await orderApi.updateDeliveryTime(orderId)
      ElMessage.success('订单发货成功')
      dialogVisible.value = false
      // 重新加载订单列表
      await fetchOrderList()
  }  finally {
    tableLoading.value = false
  }
}

// ===================== 事件处理 =====================
// ===================== 数据过滤 =====================
/**
 * 根据选中的状态筛选订单，同步到 filteredOrders
 */
const filterOrdersByStatus = () => {
  // 若原始订单列表为空，直接置空筛选结果
  if (!orders.value.length) {
    filteredOrders.value = [];
    return;
  }
  // 根据 selectedStatus 筛选对应状态的订单
  // （如果需要“全部”状态，可在 statusOptions 加 {label: '全部', value: -1}，并在此处判断 value === -1 时返回所有订单）
  filteredOrders.value = orders.value.filter(order => {
    // 匹配订单状态（注意：确保 order.status 是数字类型，与 selectedStatus 类型一致）
    return order.status === selectedStatus.value;
  });
};
/**
 * 状态筛选变更
 */
const handleStatusChange = async () => {
  orders.value = await orderApi.getOrderList(selectedStatus.value)
  // 筛选并同步
  filterOrdersByStatus();
}

/**
 * 查看订单详情
 */
const handleDetail = (row) => {
  // 深拷贝避免数据联动
  currentOrder.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
  dialogTitle.value = `订单详情（${row.order_no}）`
}

/**
 * 处理发货
 */
const handleShip = () => {
  if (!currentOrder.value.id) {
    ElMessage.warning('请选择有效的订单')
    return
  }
  // 确认发货
  ElMessageBox.confirm(
      '确定要为该订单发货吗？',
      '确认发货',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(async () => {
    await shipOrder(currentOrder.value.id)
  }).catch(() => {
    // 取消发货
    ElMessage.info('已取消发货操作')
  })
}

/**
 * 处理删除（显示确认弹窗）
 */
const handleDelete = (row) => {
  deleteOrderId.value = row.id
  deleteOrderNo.value = row.order_no
  deleteDialogVisible.value = true
}

/**
 * 确认删除
 */
const confirmDelete = async () => {
  if (!deleteOrderId.value) return
  await deleteOrder(deleteOrderId.value)
  deleteDialogVisible.value = false
  // 重置删除参数
  deleteOrderId.value = ''
  deleteOrderNo.value = ''
}

/**
 * 表格选中事件（批量操作备用）
 */
const handleSelectionChange = (val) => {
  selectedOrders.value = val
}

// ===================== 工具函数 =====================
/**
 * 状态文本转换
 */
const statusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '已发货',
    3: '已完成'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 状态标签类型
 */
const statusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'info',
    3: 'success'
  }
  return typeMap[status] || 'default'
}

/**
 * 状态标签颜色（可自定义）
 */
const statusTagColor = (status) => {
  // 如需自定义颜色可在此配置，否则使用type默认颜色
  return ''
}

/**
 * 支付方式文本转换
 */
const payTypeText = (payType) => {
  const payTypeMap = {
    0: '微信支付',
    1: '支付宝支付',
    2: '银行卡支付'
  }
  return payTypeMap[payType] || '未知支付方式'
}

/**
 * 日期时间格式化
 */
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化失败：', error)
    return dateTime
  }
}
</script>

<style scoped>
/* 外层容器样式 */
.order-table-container {
  padding: 20px;
  position: relative;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  background-color: #fff;
}

/* 筛选区域样式 */
.filter-area {
  margin-bottom: 16px;
  padding: 10px 0;
  display: flex;
  align-items: center;
}

/* 表格容器样式 */
.table-wrapper {
  height: calc(100% - 60px);
  overflow-y: auto;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 空状态样式 */
.empty-state {
  margin: 80px 0;
  text-align: center;
}

/* 表格样式优化 */
::v-deep .el-table {
  border-top: 1px solid #ebeef5;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
}

::v-deep .el-table td {
  color: #303133;
}

/* 弹窗样式优化 */
::v-deep .el-dialog__body {
  max-height: 65vh;
  overflow-y: auto;
  padding: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 16px;
}

::v-deep .el-form-item__label {
  color: #606266;
  font-weight: 500;
}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #303133;
}

/* 商品表格样式 */
::v-deep .el-table--small th {
  padding: 8px 0;
}

::v-deep .el-table--small td {
  padding: 10px 0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .order-table-container {
    padding: 15px;
  }

  ::v-deep .el-dialog {
    width: 85% !important;
  }
}

@media (max-width: 768px) {
  .order-table-container {
    padding: 10px;
    min-height: calc(100vh - 80px);
  }

  .filter-area {
    margin-bottom: 12px;
  }

  ::v-deep .el-table {
    font-size: 12px;
  }

  ::v-deep .el-table-column {
    width: auto !important;
  }

  ::v-deep .el-dialog__body {
    max-height: 55vh;
  }
}
</style>